package ltd.dujiabao.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author : DuJiabao
 * @Project : springcloud
 * @Time : 2021/5/23 12:57
 * @Desc :
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    log.info("执行自定义过滤器");
    String username = exchange.getRequest().getQueryParams().getFirst("username");
    // 由于没有包含用户名，直接过滤掉
    if (username == null) {
      log.info("用户名为null，无法登陆");
      exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
      return exchange.getResponse().setComplete();
    }
    return chain.filter(exchange);
  }

  @Override
  public int getOrder() {
    return 0;
  }
}
